<?php
error_reporting(E_ALL ^ E_NOTICE);
ini_set('memory_limit', '300M');

# Processor script
include_once('./api/classes/gbif.custom-eml.php');
include_once('./api/classes/gbif.general.php');
include_once('./config.php');
require_once('./api/classes/attach_mailer/attach_mailer_class.php');

$service = new Amazon_SQS_Client(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY);
echo '<pre>';

$request = array('QueueUrl' => $queueUrl);
$loopFlag = true;
$messageCount = 0;
try {

do{
	$readResponse = $service->receiveMessage($request);
	if ($readResponse->isSetReceiveMessageResult()) {
		$receiveMessageResult = $readResponse->getReceiveMessageResult();
		$messageList = $receiveMessageResult->getMessage();

		if(!count($messageList)) $loopFlag = false;
		foreach ($messageList as $message) {
			$delFlag = false;

			if ($message->isSetReceiptHandle() && $message->isSetBody()) {
				$receiptHandle = $message->getReceiptHandle();
				$body = trim($message->getBody());
// echo '<br> Message Body : ' . $body;
				$body = json_decode($body,true);
echo '<br> Message Body : ';
print_r($body);

				$path = dirname($body['path']) . '/';
				$foldername = basename($path);
				$file = $body['path'];
				@mkdir($pickUpPath . $body['conversionID']);

				$spreadsheet = new General($file);
				$version = $spreadsheet->getVersion();
				unset($general);
							
				switch( $version ) {
					
					case 'Checklist-1.1':
// echo '<br> In Loop 1';
						require_once ('api/classes/gbif.checklist-1-1.php');
						require_once ('api/classes/gbif.custom-eml.php');

						$tplObj = new Checklist11($file);
						
						# Make EML
						$eml = new CustomEml();
						$sheet = $tplObj->getSheet(1);
						$eml->createEmlFromWorksheet( $sheet );
						$eml->generateXml(0);
						$xml = $eml->getRawXml();
						file_put_contents($pickUpPath . $body['conversionID'] . '/eml.xml', $xml );
						
						# Make Checklist
						$tplObj->validateChecklistData();
						$tplObj->writeChecklistData($pickUpPath . $body['conversionID'] . "/");
						
						# Make metaxml
						file_put_contents($pickUpPath . $body['conversionID'] . '/meta.xml', $tplObj->meta->generateMetaData( $tplObj->getIndexes(), $tplObj->getFilenames() ) );
						
						$files = array_merge( array('eml.xml', 'meta.xml'), $tplObj->getFilenames() );
						$tplObj->zipArchive($pickUpPath . $body['conversionID'] . "/" . $body['conversionID'] . ".zip", $pickUpPath . $body['conversionID'] . "/", $files );
						break;
						

						case 'Checklist-2.1':
// echo '<br> In Loop 2';
							require_once ('api/classes/gbif.custom-eml.php');
							require_once ('api/classes/gbif.checklist-2-1.php');								
							$tplObj = new Checklist12($file);
							
							# Make EML
							$eml = new CustomEml();
							$sheet = $tplObj->getSheet(1);
							$eml->createEmlFromWorksheet( $sheet );
							$eml->generateXml(0);
							$xml = $eml->getRawXml();
							file_put_contents($pickUpPath . $body['conversionID'] . '/eml.xml', $xml );
							
							# Make Checklist
							$tplObj->buildLookUp();
							$tplObj->validateChecklistData();
							
							$tplObj->writeChecklistData($pickUpPath . $body['conversionID'] . "/");
							
							# Make metaxml
							file_put_contents($pickUpPath . $body['conversionID'] . '/meta.xml', $tplObj->meta->generateMetaData( $tplObj->getIndexes(), $tplObj->getFilenames() ) );
							
							$files = array_merge( array('eml.xml', 'meta.xml'), $tplObj->getFilenames() );
							$tplObj->zipArchive($pickUpPath . $body['conversionID'] . "/" . $body['conversionID'] . '.zip', $pickUpPath . $body['conversionID'] . "/", $files );
							break;

						case 'Checklist-3.1':
// echo '<br> In Loop 3';
							require_once ('api/classes/gbif.custom-eml.php');
							require_once ('api/classes/gbif.checklist-3-1.php');

							$tplObj = new Checklist13($file);
							
							# Make EML
							$eml = new CustomEml();
							$sheet = $tplObj->getSheet(1);
							$eml->createEmlFromWorksheet( $sheet );
							$eml->generateXml(0);
							$xml = $eml->getRawXml();
							file_put_contents($pickUpPath . $body['conversionID'] . '/eml.xml', $xml );
							
							# Make Checklist
							$tplObj->validateChecklistData();
							$tplObj->writeChecklistData($pickUpPath . $body['conversionID'] . "/");
							
							# Make metaxml
							file_put_contents($pickUpPath . $body['conversionID'] . '/meta.xml', $tplObj->meta->generateMetaData( $tplObj->getIndexes(), $tplObj->getFilenames() ) );
							
							$files = array_merge( array('eml.xml', 'meta.xml'), $tplObj->getFilenames() );
							$tplObj->zipArchive($pickUpPath . $body['conversionID'] . "/" . $body['conversionID'] . '.zip', $pickUpPath . $body['conversionID'] . "/", $files );
							break;
			}

				if($body['method'] == 'email') {
 			# if method is email
					$email_from = $body['email_from'];
					$name = "GBIF";
					$from = "nobody@gbif.org";
					$to = $email_from;
					$subject = "GBIF - Automated Darwin Core Archive Generator";
					$body = "Body Message";
					$mailer = new attach_mailer($name, $from, $to, $cc, $bcc, $subject, $body);
					$mailer->create_attachment_part($pickUpPath . $body['conversionID'] . "/" . $body['conversionID'] . '.zip', 'attachment', 'application/zip'); 
					$mailer->process_mail();
				} else {
					$fp = fopen($pickUpPath . $body['conversionID'] . '.json', 'w');
					$pickUpArray = array('status' => true, 'path' => $pickUpPathUri . $body['conversionID'] . "/" . $body['conversionID'] . '.zip');
					$ret = fwrite($fp, json_encode($pickUpArray));
					fclose($fp);
				}

				$delFlag = true;
				$messageCount++;
			} # if set message handle and set body
		
			# Deleting the message from the queue
			if($delFlag) {
				$delRequest = array('ReceiptHandle' => $receiptHandle,'QueueUrl' => $queueUrl);
				$delResponse = $service->deleteMessage($delRequest);
//				print_r($delResponse);
			}

		} # for each

	} else {
		$loopFlag = false;
	}

	if($imageCount++ > 5) $loopFlag = false;
} while($loopFlag);

} catch (Amazon_SQS_Exception $ex) {
	echo("Caught Exception: " . $ex->getMessage() . "\n<br>");
	echo("Response Status Code: " . $ex->getStatusCode() . "\n<br>");
	echo("Error Code: " . $ex->getErrorCode() . "\n<br>");
	echo("Error Type: " . $ex->getErrorType() . "\n<br>");
	echo("Request ID: " . $ex->getRequestId() . "\n<br>");
	echo("XML: " . $ex->getXML() . "\n<br>");
}

echo 'Script Executed Successfully';
echo '<br>Message Count: ' . $messageCount;
?>